package com.mmdccj.yugu.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mmdccj.yugu.dto.PostDto;
import com.mmdccj.yugu.entity.Post;
import com.mmdccj.yugu.mapper.PostMapper;
import com.mmdccj.yugu.service.PostService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: star_
 * @date: 2023-11-30 18:46
 */
@Slf4j
@Service
public class PostServiceImpl implements PostService {
    // 自动注入PostMapper实例
    @Autowired
    private PostMapper postMapper;

    /**
     * 创建动态
     *
     * @param post 动态
     */

    @Override
    public void insertPost(Post post) {
        // 插入基本数据
        postMapper.insertPost(post);
        // 当该动态添加了图片时
        if (post.getImageList() != null && post.getImageList().size() > 0) {
            // 插入图片到图片表
            postMapper.insertPostImage(post);
        }

    }

    /**
     * 分页查询
     *
     * @param currentPage 当前页码
     * @param pageSize    每页大小
     * @return PageInfo<PostDto>
     */
    @Override

    public PageInfo<PostDto> getPost(int currentPage, int pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        // 查询数据
        List<PostDto> list = postMapper.selectAllPost(); // 动态的基本数据
        log.info("查询的数据: {}", list);

        return new PageInfo<>(list);
    }

    /**
     * 获取动态中评论的数量
     *
     * @param postId
     * @param type
     * @return Integer
     */
    @Override
    public Integer getCommentCount(String postId, String type) {
        // Todo 可以根据 type 来调用不同的mapper来获取不同评论的数量
        return postMapper.selectCommentCount(postId);
    }

    @Override
    @Transactional
    public boolean like(String userId, String postId) {
        if (postMapper.checkLike(userId, postId) == 0) {
            Integer likes = postMapper.like(postId);
            postMapper.updateLike(postId, likes + 1);
            postMapper.insertLikeTo(postId, userId);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public PostDto getOne(String postId) {
        return postMapper.selectOne(postId);
    }

    @Override
    public PageInfo<PostDto> getMyPost(int currentPage, int pageSize, String userId) {
        PageHelper.startPage(currentPage, pageSize);
        // 查询数据
        List<PostDto> list = postMapper.selectAllMyPost(userId); // 动态的基本数据
        log.info("查询的数据: {}", list);

        return new PageInfo<>(list);
    }
}
